<?php
namespace Braintwister\Controller;
use Common\Controller\BraintwisterController;
class WxpayController extends BraintwisterController {

    public function __construct()
    {
        $sessionid = 'PHPSESSID='.$this->getSessionId();

        $getsessionid = $_SERVER['HTTP_COOKIE'];
        if ($sessionid!=$getsessionid){
            $this->returnData('','状态已过期请重新授权',400);
        }
    }

    /**
     * 微信支付
     */
    public function wxpay(){

        $wxusers_id = I('post.wxusers_id','','int');
        $total_fee = I('post.total_fee','','int');
        $openid = I('post.openid','','htmlspecialchars');
        $appid = I('post.appid','','htmlspecialchars');



        if ($wxusers_id==""||$total_fee==""||$appid==""){
            $this->returnData('','参数错误',401);
        }



        $total_fee = $total_fee*100;


        $wxpay  = new \Braintwister\Model\WxpayhistoryModel($appid);

        $body = '脑筋急转弯支付查看答案';
        $order = $wxpay->setout_trade_no();
        $params = array(
            'body'=>$body,
            'out_trade_no'=>$order,
            'total_fee'=>$total_fee,
            'trade_type'=>'JSAPI',
            'openid'=>$openid,
        );


        $res = $wxpay->unifiedOrder2( $params );

        if ($res[return_code]!='SUCCESS'){
            $this->returnData('','失败',100);
        }

        $timeStamp = time();
        $data = array();

        $data['appId'] = $res[appid];
        $data['timeStamp'] = "$timeStamp";
        $data['nonceStr'] = $wxpay->genRandomString();
        $data['package'] = 'prepay_id='.$res[prepay_id];
        $data['signType'] = 'MD5';
        $data['paySign'] = $wxpay->MakeSign($data);

        $arr = array(
            'appid'=>$res[appid],
            'mch_id'=>$res[mch_id],
            'body'=>$body,
            'out_trade_no'=>$order,
            'total_fee'=>$total_fee,
            'wxusers_id'=>$wxusers_id,
            'ispay'=>0,
            'prepay_id'=>$res[prepay_id],
            'createtime'=>time(),
        );

        M('Wxpayhistory')->data($arr)->add();
        $this->returnData($data,'成功',200);

    }

    /**
     * 更新支付状态
     */
    public function chekpay(){

        $wxusers_id = I('post.wxusers_id','','int');
        $ispay = I('post.ispay','0','int');
        $appid = I('post.appid','','htmlspecialchars');

        if (!$wxusers_id||!$ispay){
            $this->returnData('','参数错误',401);
        }

        $where['wxusers_id'] = $wxusers_id;
        $where['appid'] = $appid;
        $id = "";
        $id = M('Wxpayhistory')->where($where)->order('wxpayhistory_id desc')->getField('wxpayhistory_id');

        if ($id==""){
            $this->returnData('','没有订单',200);
        }

        $data = array(
            'ispay'=>$ispay,
            'updatetime'=>time(),
        );

        M('Wxpayhistory')->where($where)->save($data);

        $this->returnData('','支付成功',200);

    }


}
